# 存储相关类
import os

from .err import StorageErr
from pathlib import Path
from djangomodel import settings

# 标准存储类
class BaseStorage:
    def __init__(self):
        pass

    # 保存
    def save(self, **kwargs):
        pass

    # 下载
    def download(self, **kwargs):
        pass

    # 删除
    def delete(self, **kwargs):
        pass


# 使用本地存储存储类
class LocalStorage(BaseStorage):

    def __init__(self):
        if hasattr(settings, 'LOCAL_STORAGE_PATH'):
            self.path = settings.LOCAL_STORAGE_PATH
        else:
            self.path = settings.BASE_DIR / Path("storage")
            if not self.path.exists():
                self.path.mkdir(parents=True, exist_ok=False)

    def save(self,file_name,file_data):
        try:
            file_path = self.path / Path(file_name)
            with open(file_path,"wb") as f:
                f.write(file_data)
            return True
        except Exception as e:
            raise StorageErr(f"文件保存失败！err:{e.__str__()}")

    def read(self,file_name):
        try:
            file_path = self.path / Path(file_name)
            with open(file_path,"rb") as f:
                data = f.read()
            return data
        except Exception as e:
            raise StorageErr(f"文件读取失败！err:{e.__str__()}")

    def delete(self,file_name):
        try:
            file_path = self.path / Path(file_name)
            os.remove(file_path)
        except Exception as e:
            raise StorageErr(f"文件删除失败！err:{e.__str__()}")